import React, { useState, useEffect } from 'react';
import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid,
} from 'recharts';
import { cloneDeep } from 'lodash';
import { Button } from 'antd';

// 一定要61个 不然不能填充满
function initData() {
  const data = []
  for (let i = 0; i <= 60; i++) {
    const item = {
      x: i,
      y: 0
    }
    data.push(item)
  }
  return data;
}

const CartChart: React.FC<any> = (props => {

  const initdata = initData()
  const [data, setData] = useState<any>(initdata)

  let setIntervalData: any = null;
  useEffect(() => {
    setIntervalData = setInterval(() => {
      changeData()
    }, 1000)
    return (() => {
      clearInterval(setIntervalData)
    })
  }, [])

  const changeData = () => {

    const value = (Math.random() * 100).toFixed(2);
    const item = {
      x: 0,
      y: value
    }
    // 往后添加
    data.push(item);
    data.shift();

    const newData: any[] = [];
    data.forEach((item: any, index: number) => {
      newData.push({ x: index, y: item.y })
    })
    setData(cloneDeep(newData))

  }

  return (
    <div>
      <Button type="primary" onClick={() => { changeData() }}>新增数据</Button>
      <AreaChart
        width={500}
        height={400}
        data={data}
        margin={{
          top: 10, right: 30, left: 0, bottom: 0,
        }}
      >
        <CartesianGrid stroke={'#8884d8'} />
        <XAxis
          dataKey="x"
          interval={0}
          domain={[0, 60]}
          ticks={[0, 10, 20, 30, 40, 50, 60]}
          stroke="rgba(0,0,0,0)" />

        <YAxis
          interval={0}
          stroke="rgba(0,0,0,0)"
          domain={[0, 100]}
          ticks={[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]}
        />
        <Area
          type="monotone"
          dataKey="y"
          stroke="#8884d8"
          fill="#8884d8"
          isAnimationActive={false} />
      </AreaChart>
    </div>

  )
})

export default CartChart;